package com.gs.zsmanage.config.shiroconfig;

import com.gs.zsmanage.entity.Unit;
import com.gs.zsmanage.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


//Authentication 身份认证/登陆
//Authorization 授权 （权限认证）
//principals 身份、主体的标志属性
//credentials 证明/凭证


public class UserRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    UserService userService;

    //登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //角色
        String name = (String) token.getPrincipal();
        //证明
        String password = new String((char[]) token.getCredentials());

        Unit unit = userService.getUnitByNick(name);

        logger.info("用户[{}]进入登录验证", name);

        if (unit == null || !name.equals(unit.getNick())) {
            throw new UnknownAccountException("用户名不存在");
        } else {
            if (!password.equals(unit.getPassword())) {
                throw new IncorrectCredentialsException("密码错误");
            }
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                name,
                password,
                ByteSource.Util.bytes(name),//经验证。设置username、pwd都没问题
                getName() //realm name
        );

        logger.info("用户[{}]进入登录验证成功", name);
        return info;
    }


    //授权管理:判断登陆用户拥有哪些访问资源权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        logger.info("用户[{}]进入授权验证", name);
        try {
            List<String> permissions = new ArrayList<String>();

            permissions.add("/**");

            info.setStringPermissions(new HashSet<>(permissions));
            logger.info("用户[{}]授权认证完成", name);
            return info;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
